package com.hmy.pig.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hmy.pig.domain.HmyPig;
import com.hmy.pig.service.PigService;
import com.hmy.pig.service.impl.HmyPigServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
*  * @param null
* @return
* @author kdq
* @date 2024/2/20 16:57
* @description 批量插入猪只档案监听器
*/
@Component
public class ExcelListener extends AnalysisEventListener<HmyPig> implements ReadListener<HmyPig> {

    /**
     * 每隔5条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    /*
     * 定义一千条数据的列表
     */
    private List<HmyPig> dataList = new ArrayList<>(BATCH_COUNT);


    @Autowired
    private HmyPigServiceImpl hmyPigService;

    @Autowired
    private PigService pigService;



    public ExcelListener(HmyPigServiceImpl hmyPigService) {
        this.hmyPigService = hmyPigService;
    }

    @Override
    public void invoke(HmyPig data, AnalysisContext context) {
        dataList.add(data);
        if (dataList.size() == BATCH_COUNT) {
            hmyPigService.batchInsert(dataList);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 数据读取完成后，批量插入到数据库中
        if (!dataList.isEmpty()) {
            hmyPigService.batchInsert(dataList);
        }
    }


}

